import UIKit

class ToastView: UIView {
    
    private let toastLabel = UILabel()
    
    init(message: String, frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        toastLabel.text = message
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    private func setupUI() {
        toastLabel.textColor = .white
        toastLabel.font = UIFont.systemFont(ofSize: 16)
        toastLabel.textAlignment = .center
        toastLabel.backgroundColor = UIColor(white: 0, alpha: 0.7)
        toastLabel.layer.cornerRadius = 8
        toastLabel.clipsToBounds = true
        
        addSubview(toastLabel)
        toastLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            toastLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
            toastLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
            toastLabel.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: 16),
            toastLabel.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -16)
        ])
    }
    
    func show(duration: TimeInterval) {
        guard let window = UIApplication.shared.windows.first else { return }
        window.addSubview(self)
        self.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: window.topAnchor, constant: 100),
            self.centerXAnchor.constraint(equalTo: window.centerXAnchor),
            self.widthAnchor.constraint(equalToConstant: 200)
        ])
        
        DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
            self.removeFromSuperview()
        }
    }
}
